package com.apidoc.core;

import com.apidoc.annotation.ApiOperation;
import com.apidoc.annotation.ApiParam;
import com.apidoc.config.ApiDocProperties;
import com.apidoc.model.ApiDocInfo;
import com.apidoc.model.ApiInfo;
import com.apidoc.model.ControllerInfo;
import com.apidoc.model.ParameterInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class ApiDocGenerator {
    private final ApiDocScanner apiDocScanner;
    private final ApiDocProperties properties;
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    public ApiDocGenerator(ApiDocScanner apiDocScanner, ApiDocProperties properties) {
        this.apiDocScanner = apiDocScanner;
        this.properties = properties;
    }

    /**
     * 生成API文档主方法
     */
    public void generate() {
        try {
            // 1. 确保输出目录存在
            File outputDir = new File(properties.getOutputPath());
            if (!outputDir.exists()) {
                outputDir.mkdirs();
            }

            // 2. 扫描API信息
            ApiDocInfo docInfo = apiDocScanner.scan();

            // 3. 生成JSON文档
            generateJsonDoc(docInfo, outputDir);

        } catch (Exception e) {
            throw new RuntimeException("生成API文档失败", e);
        }
    }

    /**
     * 计算总接口数
     */
    public int calculateTotalApis(ApiDocInfo docInfo) {
        if (docInfo == null || docInfo.getControllers() == null) {
            return 0;
        }
        return docInfo.getControllers().stream()
                .filter(controller -> controller.getApis() != null)
                .mapToInt(controller -> controller.getApis().size())
                .sum();
    }

    /**
     * 生成JSON文档
     */
    private void generateJsonDoc(ApiDocInfo docInfo, File outputDir) {
        try {
            // 添加生成时间信息（如果需要）
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String generateTime = sdf.format(new Date());

            // 可以在这里向docInfo添加额外信息，如生成时间等

            File jsonFile = new File(outputDir, "api-docs.json");
            objectMapper.writerWithDefaultPrettyPrinter().writeValue(jsonFile, docInfo);
            System.out.println("JSON文档生成成功：" + jsonFile.getAbsolutePath());
        } catch (IOException e) {
            throw new RuntimeException("生成JSON文档失败", e);
        }
    }

    /**
     * 检查指定控制器是否存在
     */
    public boolean hasController(ApiDocInfo docInfo, String className) {
        if (docInfo == null || docInfo.getControllers() == null) {
            return false;
        }
        return docInfo.getControllers().stream()
                .anyMatch(controller -> className.equals(controller.getClassName()));
    }

    /**
     * 获取指定控制器信息
     */
    public ControllerInfo getController(ApiDocInfo docInfo, String className) {
        if (docInfo == null || docInfo.getControllers() == null) {
            return null;
        }
        return docInfo.getControllers().stream()
                .filter(controller -> className.equals(controller.getClassName()))
                .findFirst()
                .orElse(null);
    }


}
